﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MsgPack.Serialization;
using System.IO;

namespace IPrinting
{
    public class MsgPackHandler
    {
        public static byte[] ConvertToBytes<T>(T t)
        {
            var serializer = SerializationContext.Default.GetSerializer<T>();
            byte[] dataBody = null;
            using (var stream = new MemoryStream())
            {
                serializer.Pack(stream, t);
                dataBody = stream.ToArray();
            }
            return dataBody;
        }

        public static T ConvertToObject<T>(byte[] buffer) where T : class
        {
            var serializer = SerializationContext.Default.GetSerializer<T>();
            using (var stream = new MemoryStream(buffer, 0, buffer.Length))
            {
                T pack = serializer.Unpack(stream) as T;
                return pack;
            }
        }

        public static T ConvertToObject<T>(byte[] buffer, int offset, int length) where T : class
        {
            var serializer = SerializationContext.Default.GetSerializer<T>();
            using (var stream = new MemoryStream(buffer, offset, length))
            {
                T pack = serializer.Unpack(stream) as T;
                return pack;
            }
        }
    }
}
